﻿using OpenCvSharp.WpfExtensions;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SuporeSliplampApp.Models;
using System.Windows.Forms;
using System.IO;

namespace SuporeSliplampApp.Views
{
    /// <summary>
    /// ImgProcessView.xaml 的交互逻辑
    /// </summary>
    public partial class ImgProcessView : System.Windows.Window
    {

        public static event EventHandler<ListControlModel> imgprocessDelegate;

        private BitmapSource originalImage;
        private BitmapSource adjustedImage;

        public ImgProcessView(BitmapSource image)
        {
            InitializeComponent();

            originalImage = image;
            imageControl.Source = originalImage;
           
        }

        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (originalImage == null)
            {
                return;
            }

            contrastValue.Content = contrastSlider.Value.ToString("F2");
            brightnessValue.Content = brightnessSlider.Value.ToString("F2");
            saturationValue.Content = saturationSlider.Value.ToString("F2");
            hueValue.Content = hueSlider.Value.ToString("F0");


            double contrast = contrastSlider.Value;
            double brightness = brightnessSlider.Value;
            double saturation = saturationSlider.Value;
            double hue = hueSlider.Value;

            adjustedImage = AdjustImage(originalImage , contrast, brightness, saturation, hue);
            imageControl.Source = adjustedImage;

        }



        private BitmapSource AdjustImage(BitmapSource source, double contrast, double brightness, double saturation, double hue)
        {
            // Convert BitmapSource to Mat
            Mat mat = source.ToMat();

            // Adjust contrast and brightness
            mat.ConvertTo(mat, -1, contrast, (brightness - 1) * 255);

            // Convert to HSV for saturation and hue adjustments
            Mat hsv = new Mat();
            Cv2.CvtColor(mat, hsv, ColorConversionCodes.BGR2HSV);

            // Split HSV channels
            Mat[] hsvChannels = Cv2.Split(hsv);

            // Adjust saturation
            hsvChannels[1] *= saturation;

            double opencvhue = hue / 2.00;
            // Adjust hue
            hsvChannels[0].ConvertTo(hsvChannels[0], -1, 1, opencvhue);

            // Merge channels and convert back to BGR
            Cv2.Merge(hsvChannels, hsv);
            Cv2.CvtColor(hsv, mat, ColorConversionCodes.HSV2BGR);

            return mat.ToBitmapSource();
        }


        private void Slider_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            Slider slider = sender as Slider;
            System.Windows.Point position = e.GetPosition(slider);

            double relativePosition = position.X / slider.ActualWidth;
            double newValue = slider.Minimum + (relativePosition * (slider.Maximum - slider.Minimum));

            slider.Value = newValue;
        }


        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            imageControl = null;
            this.Close();
        }

        private void Reset_Click(object sender, RoutedEventArgs e)
        {
            contrastSlider.Value = 1;
            brightnessSlider.Value = 1;
            saturationSlider.Value = 1.5;
            hueSlider.Value = 0;
            imageControl.Source = originalImage;
        }

        private void Apply_Click(object sender, RoutedEventArgs e)
        {
            BitmapSource finalimage = adjustedImage ?? originalImage;
            if (finalimage != null)
            {
                WriteableBitmap bitmap = new WriteableBitmap(finalimage);
                string path = DateTime.Now.ToString("yyyyMMddHHmmfff") + "adjusted" + ".bmp";

                using (FileStream stream = new FileStream(path, FileMode.Create))
                {
                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(bitmap));
                    encoder.Save(stream);
                }

                ListControlModel model = new ListControlModel { ImgPath = System.AppDomain.CurrentDomain.BaseDirectory + path, Name = path };

                imgprocessDelegate?.Invoke(this, model);
            }
            else
            {
                return;
            }

            this.Close();

        }


    }
}
